import cooApp, {
    Widget,
    basicWidgets,
    Util,
    ui,
    coolink,
} from 'coolink-ts'
import { Colors } from '../../config'
import { px } from '../../base/func'
import Center from '../../widgets/Center'
import baseinfo from '../../base/baseInfo'
import { showAutoHideToast } from '../../widgets/Toast'

const { Page, AppBar, Container, Text, Button, Image, Input, ScrollView } = basicWidgets

export default class EditPage extends Widget<any, any> {
    state = {
        curRules: '',
        backgroundGradient: {
            colors: [0xFF9C04D0, 0xFFFF60D5],
            type: 'linear',
            begin: 'centerLeft',
            end: 'centerRight'
        },
        boxShadow: {
            color: Colors.Black,
            blurRadius: 24,
            spreadRadius: 0,
        },
        showRulePart: true,
        rulePartHeight: 180,
        showTurnPart: true,
        turnPartHeight: 275,
        showBgPart: true,
        bgPartHeight: 275,

        turnItemInfos: [],
        turnStyles: [],

    }
    ruleValue: any;
    _changeRule = ''
    _turnItemInfos = []
    _turnStyle = []

    // 从缓存读取编辑存储的列表，通过选中下拉列表LIst组件
    // Table显示选中的列表 列表名称 列表属性 编辑
    // 保存后新增或者替换原有的一列属性

    widgetDidMount() {
        cooApp.pageDidShow()

        this.showCurRules();
        this.showTurnsContent();
        this.showStyleContent();
    }

    showCurRules = async () => {
        let _localRule = await coolink.storage.getKey('singleRule');
        // Util.log("lxw editPage localRule:", _localRule.value)
        if (_localRule.value) {
            // this.setState({ curRules: _localRule });
            this.ruleValue.setValue(_localRule.value);
        } else {
            let _defaultRule = '1、进入游戏转盘页面，点击开始游戏，也可以推送到电视端后，两端同步。2、转盘结束，弹出最终结果，进入下一环节。3、最终解释权不在你这里！';
            // this.setState({ curRules: _defaultRule });
            this.ruleValue.setValue(_defaultRule);
        }
    }
    showTurnsContent = async () => {
        let _localAwards = await coolink.storage.getKey("singleAwards");
        Util.log("lxw showRules localAwards:", _localAwards.value)
        if (_localAwards.value) {
            Util.log("lxw showAwardsPart------------1");
            let _localContentArray = [];
            for (let i = 0; i < JSON.parse(_localAwards.value).awardNameList.length; i++) {
                _localContentArray.push({
                    name: JSON.parse(_localAwards.value).awardNameList[i],
                    ratio: JSON.parse(_localAwards.value).awardRatioList[i],
                    // color: JSON.parse(_localAwards.value).awardBgList[i]
                });
            }
            Util.log("lxw showAwardsPart1:" + JSON.stringify(_localContentArray));
            this._turnItemInfos = _localContentArray;
            this.setState({ turnItemInfos: _localContentArray })
        } else {
            Util.log("lxw showAwardsPart------------2");
            let _defaultContentObj = {
                "awardNameList": ["喝半杯", "真心话", "上家曝光", "下家曝光", "大家干杯", "男士喝光", "PASS", "女士干杯", "和异性交杯", "找人干杯", "自己唱首歌", "干一杯"],
                "awardRatioList": [1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12],
                // "awardBgList": [Colors.Transparent.toString(), Colors.Lightgray.toString(), Colors.Transparent.toString(), Colors.Lightgray.toString(), Colors.Transparent.toString(), Colors.Lightgray.toString(), Colors.Transparent.toString(), Colors.Lightgray.toString(), Colors.Transparent.toString(), Colors.Lightgray.toString(), Colors.Transparent.toString(), Colors.Lightgray.toString()]
            }
            let _newContentArray = []
            for (let i = 0; i < _defaultContentObj.awardNameList.length; i++) {
                _newContentArray.push({
                    name: _defaultContentObj.awardNameList[i],
                    ratio: _defaultContentObj.awardRatioList[i],
                    // color: _defaultContentObj.awardBgList[i]
                })
            }
            Util.log("lxw showAwardsPart1:" + JSON.stringify(_newContentArray));
            this._turnItemInfos = _newContentArray;
            this.setState({ turnItemInfos: _newContentArray });
        }
    }
    showStyleContent() {
        let _localStyles = coolink.storage.getKey("singleStyles");
        Util.log("lxw showRules localAwards:", _localStyles)
        if (_localStyles) {
            // let _localContentObj = {

            // }
        } else {
            let _defaultContentArray = [
                { key: 'awardBgUrl', name: "转盘背景图", value: 'https://coolink.coocaa.com/applet/coo-turns/turnbg.png' },
                { key: 'bgWidth', name: "转盘背景图宽度", value: 350.0 },
                { key: 'bgHeight', name: "转盘背景图高度", value: 350.0 },
                { key: 'contentWidth', name: "转盘内容文本宽度", value: 240.0 },
                { key: 'contentHeight', name: "转盘内容文本高度", value: 240.0 },
                { key: 'secondUrl', name: "指针图片", value: 'https://coolink.coocaa.com/applet/coo-turns/center.png' },
                { key: 'secondWidth', name: "指针宽度", value: 50.0 },
                { key: 'secondHeight', name: "指针高度", value: 50.0 },
                { key: 'circle', name: "转的总圈数", value: 4 },
                { key: 'fontSize', name: "转盘文字大小", value: 10 },
            ]
            this.setState({ turnStyles: _defaultContentArray })
        }
    }

    onRuleChange(value: any) {
        // Util.log("lxw onRuleChange", value.value);
        // this.ruleValue.setValue(value);
        this._changeRule = value.value;
    }
    onAwardNameChange(value: any, index: number) {
        this._turnItemInfos[index].name = value.value;
    }
    onAwardRatioChange(value: any, index: number) {
        this._turnItemInfos[index].ratio = value.value;
    }
    deleteItem(index: number) {
        this._turnItemInfos.splice(index, 1);
        // Util.log("lxw deleteItem after 3", this._turnItemInfos);
        this.setState({ turnItemInfos: this._turnItemInfos })
    }
    addItem() {
        let _item = {
            name: "选项" + (this.state.turnItemInfos.length + 1),
            ratio: 0.1,
            color: Colors.Transparent
        }
        let _oldArray = this.state.turnItemInfos;
        if (_oldArray.length == 12) {
            showAutoHideToast('最多只能添加12项。');
        } else {
            _oldArray.push(_item);
            // this._turnItemInfos.push(_item);
            Util.log("lxw addItem after 2", _oldArray);
            this.setState({ turnItemInfos: _oldArray })
        }
    }
    saveRulesEdit() {
        Util.log("lxw saveRulesEdit", this._changeRule);
        // this.setState({ curRules: this._changeRule });
        coolink.storage.setKey('singleRule', this._changeRule)
        let { setRuleInfo } = baseinfo.ruleInfo;
        setRuleInfo(this._changeRule);
        showAutoHideToast('游戏规则更改成功。');
    }
    saveTurnEdit() {
        Util.log("lxw saveTurnEdit", this._turnItemInfos);
        if (this._turnItemInfos.length < 2) {
            showAutoHideToast('选项至少超过两项');
        } else {
            let _saveLocalTurnsInfo = {
                awardNameList: [],
                awardRatioList: [],
                // awardBgList: [],
            }
            let _allRatio = 0;
            for (let j = 0; j < this._turnItemInfos.length; j++) {
                _saveLocalTurnsInfo.awardNameList[j] = this._turnItemInfos[j].name;
                _saveLocalTurnsInfo.awardRatioList[j] = this._turnItemInfos[j].ratio;
                // _saveLocalTurnsInfo.awardBgList[j] = this._turnItemInfos[j].color;
                _allRatio += parseFloat(this._turnItemInfos[j].ratio);
            }
            Util.log("lxw saveTurnEdit2", _allRatio, _saveLocalTurnsInfo);
            // if (_allRatio > 0.9999) {
            coolink.storage.setKey('singleAwards', JSON.stringify(_saveLocalTurnsInfo))
            let { setTurnsInfo } = baseinfo.turnsInfo;
            setTurnsInfo(_saveLocalTurnsInfo);
            showAutoHideToast('保存成功');
            // } else {
            //     showAutoHideToast('概率总和只能等于1，请重新编辑');
            // }
        }
    }
    saveBgEdit() {
        Util.log("lxw saveBgEdit");
    }
    changePartShow(part: number) {
        if (part == 1) {
            if (this.state.showRulePart) {
                this.setState({ rulePartHeight: 30 })
            } else {
                this.setState({ rulePartHeight: 170 })
            }
            this.setState({ showRulePart: !this.state.showRulePart })
        } else if (part == 2) {
            if (this.state.showTurnPart) {
                this.setState({ turnPartHeight: 30 })
            } else {
                this.setState({ turnPartHeight: 275 })
            }
            this.setState({ showTurnPart: !this.state.showTurnPart })
        } else if (part == 3) {
            if (this.state.showBgPart) {
                this.setState({ bgPartHeight: 30 })
            } else {
                this.setState({ bgPartHeight: 275 })
            }
            this.setState({ showBgPart: !this.state.showBgPart })
        }
    }

    render() {
        Util.log("lxw render", this.state.turnItemInfos);
        const appbarHeight = ui.appbarHeight;
        const statusBarHeight = Math.round(ui.statusBarHeight);
        const bottomBarHeight = ui.bottomBarHeight;
        const clientHeight = ui.screenHeight - statusBarHeight - appbarHeight - bottomBarHeight;

        return (
            <Page>
                <Container relative={true} width={ui.screenWidth} height={ui.screenHeight}>
                    <Image absolute={{ top: 0, left: 0 }} fit="fill" src='https://coolink.coocaa.com/applet/coo-turns/wheelpageBg.png' height={ui.screenHeight} width={ui.screenWidth}></Image>
                    <Container relative={true} absolute={{ top: 0, left: 0 }} width={ui.screenWidth} height={clientHeight}>
                        <Container
                            height={px(this.state.rulePartHeight)}
                            width={ui.screenWidth}
                            margin={{ top: px(100) }}
                            justifyContent="center"
                            alignItems="center"
                        >
                            <Container row height={px(30)} width={px(350)} onTap={() => { this.changePartShow(1) }}>
                                <Center height={px(26)} width={px(100)}>
                                    <Text width={px(100)} align="left" size={px(20)} color={Colors.White}>活动规则</Text>
                                </Center>
                                {/* <Center height={px(26)} width={px(40)}>
                                    <Text size={px(14)} width={px(40)} color={Colors.White} align="left">{(this.state.showRulePart) ? "收起" : "展开"}</Text>
                                </Center> */}
                            </Container>
                            {
                                this.state.showRulePart &&
                                <Container width={px(350)}>
                                    <Input
                                        ref={(e) => this.ruleValue = e}
                                        ress
                                        height={px(100)}
                                        maxLines={3}
                                        placeholder="请确认规则"
                                        textStyle={{ color: Colors.White, size: 14 }}
                                        onChange={(value) => this.onRuleChange(value)}
                                    >
                                    </Input>
                                    <Button
                                        width={px(150)}
                                        height={px(40)}
                                        margin={{ left: px(100) }}
                                        borderRadius={px(25)}
                                        justifyContent="center" alignItems="center"
                                        backgroundGradient={this.state.backgroundGradient as any}
                                        boxShadow={this.state.boxShadow}
                                        onTap={() => this.saveRulesEdit()}
                                    >
                                        <Text text="保存" color={0xffffffff} size={px(20)}></Text>
                                    </Button>
                                </Container>
                            }
                        </Container>

                        <Container
                            width={ui.screenWidth}
                            height={px(this.state.turnPartHeight)}
                            margin={{ top: px(20) }}
                            justifyContent="center"
                            alignItems="center"
                        >
                            <Container row height={px(30)} width={px(350)} onTap={() => { this.changePartShow(2) }}>
                                <Center height={px(26)} width={px(100)}>
                                    <Text width={px(100)} align="left" size={px(20)} color={Colors.White}>转盘内容</Text>
                                </Center>
                                {/* <Center height={px(26)} width={px(40)}>
                                    <Text size={px(14)} width={px(40)} color={Colors.White} align="left">{(this.state.showTurnPart) ? "收起" : "展开"}</Text>
                                </Center> */}
                            </Container>
                            {
                                this.state.showTurnPart &&
                                <Container width={px(350)}>
                                    <Container
                                        // width={px(350)}
                                        height={px(180)}
                                        margin={{ top: px(10) }}
                                        justifyContent="center"
                                        alignItems="center"
                                        border={{
                                            color: Colors.Black,
                                            width: px(0.5),
                                            side: ['top', 'bottom', 'left', 'right']
                                        }}
                                    >
                                        <ScrollView direction={"vertical"} width={px(350)} height={px(180)}>
                                            {
                                                this.state.turnItemInfos.map((item, index) => {
                                                    return (
                                                        <Container key={item.name} row width={px(350)} height={px(30)} mainAxisAlignment="center" backgroundColor={(index % 2 == 0) ? Colors.Lightgray : Colors.Darkgray}>
                                                            <Input size={16} width={px(200)} height={px(30)} textAlign="center" maxLength={7} value={item.name} textStyle={{ color: Colors.White }}
                                                                onChange={(value) => this.onAwardNameChange(value, index)}>
                                                            </Input>
                                                            {/* <Input size={16} width={px(75)} height={px(30)} textAlign="center" value={item.ratio} textStyle={{ color: Colors.White }}
                                                                onChange={(value) => this.onAwardRatioChange(value, index)}>
                                                            </Input> */}
                                                            <Container
                                                                width={px(75)}
                                                                height={px(30)}
                                                                borderRadius={px(25)}
                                                                justifyContent="center"
                                                                alignItems="center"
                                                                onTap={() => { this.deleteItem(index) }}
                                                            >
                                                                <Text text="删除" size={px(18)} color={Colors.White}></Text>
                                                            </Container>
                                                        </Container>
                                                    )
                                                })
                                            }
                                        </ScrollView>
                                    </Container>
                                    <Container row>
                                        <Button
                                            width={px(120)}
                                            height={px(40)}
                                            margin={{ left: px(33), top: px(10), right: px(17) }}
                                            borderRadius={px(25)}
                                            justifyContent="center" alignItems="center"
                                            backgroundGradient={this.state.backgroundGradient as any}
                                            boxShadow={this.state.boxShadow}
                                            onTap={() => this.addItem()}
                                        >
                                            <Text text="新增" color={0xffffffff} size={px(20)}></Text>
                                        </Button>
                                        <Button
                                            width={px(120)}
                                            height={px(40)}
                                            margin={{ left: px(17), top: px(10), right: px(33) }}
                                            borderRadius={px(25)}
                                            justifyContent="center" alignItems="center"
                                            backgroundGradient={this.state.backgroundGradient as any}
                                            boxShadow={this.state.boxShadow}
                                            onTap={() => this.saveTurnEdit()}
                                        >
                                            <Text text="保存" color={0xffffffff} size={px(20)}></Text>
                                        </Button>
                                    </Container>
                                </Container>
                            }
                        </Container>

                        {/* 转盘样式编辑部分 */}
                        {/* <Container
                            width={px(351)}
                            height={px(this.state.bgPartHeight)}
                            margin={{ left: px((ui.screenWidth - 350) * 0.5) }}
                        >
                            <Container row height={px(30)} onTap={() => { this.changePartShow(3) }}>
                                <Center height={px(26)} width={px(100)}>
                                    <Text size={px(20)} color={Colors.White}>转盘样式</Text>
                                </Center>
                                <Center height={px(26)} width={px(40)}>
                                    <Text size={px(14)} width={px(40)} color={Colors.White} align="left">{(this.state.showBgPart) ? "收起" : "展开"}</Text>
                                </Center>
                            </Container>
                            {
                                this.state.showBgPart &&
                                <Container>
                                    <Container
                                        width={px(351)}
                                        height={px(181)}
                                        margin={{ top: px(10) }}
                                        justifyContent="center"
                                        alignItems="center"
                                        border={{
                                            color: Colors.Black,
                                            width: px(0.5),
                                            side: ['top', 'bottom', 'left', 'right']
                                        }}
                                    >
                                        <ScrollView direction={"vertical"} width={350} height={px(180)}>
                                            {
                                                this.state.turnStyles.map((item2, index) => {
                                                    return (
                                                        <Container key={item2.name} row width={px(350)} height={px(30)} mainAxisAlignment="center" backgroundColor={(index % 2 == 0) ? Colors.Lightgray : Colors.Darkgray}>
                                                            <Input size={16} width={px(150)} height={px(30)} textAlign="center" value={item2.name} textStyle={{ color: Colors.White }}></Input>
                                                            <Input size={16} width={px(200)} height={px(30)} textAlign="center" value={item2.value} textStyle={{ color: Colors.White }}></Input>
                                                        </Container>
                                                    )
                                                })
                                            }
                                        </ScrollView>
                                    </Container>
                                    <Container row>
                                        <Container
                                            width={px(120)}
                                            height={px(40)}
                                            margin={{ left: px(115), top: px(10) }}
                                            borderRadius={px(25)}
                                            justifyContent="center" alignItems="center"
                                            backgroundGradient={this.state.backgroundGradient as any}
                                            boxShadow={this.state.boxShadow}
                                            onTap={() => this.saveBgEdit()}
                                        >
                                            <Text text="保存" color={0xffffffff} size={px(20)}></Text>
                                        </Container>
                                    </Container>
                                </Container>
                            }
                        </Container> */}
                    </Container>
                </Container>
            </Page >
        )
    }
}